/*** Eclipse Class Decompiler plugin, copyright (c) 2012 Chao Chen (cnfree2000@hotmail.com) ***/
package com.inxedu.os.common.controller;

import com.google.gson.Gson;
import com.inxedu.os.common.constants.CommonConstants;
import com.inxedu.os.common.util.DateUtils;
import com.inxedu.os.common.util.FileUploadUtils;
//import com.inxedu.os.common.util.PDFUtils;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller
@RequestMapping({ "/image" })
public class ImageUploadController extends BaseController {
	private static Logger logger = LoggerFactory.getLogger(ImageUploadController.class);
	private List<String> fileTypeList;

	public ImageUploadController() {
	}

	private String getProjectRootDirPath(HttpServletRequest request) {
		return request.getSession().getServletContext().getRealPath("/");
	}

	@RequestMapping(value = { "/gok4" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	public String gok4(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "uploadfile", required = true) MultipartFile uploadfile, @RequestParam(value = "param", required = false) String param, @RequestParam(value = "fileType", required = true) String fileType, @RequestParam(value = "pressText", required = false) String pressText) {
		try {
			long maxSize = 4096000L;
			System.out.println(uploadfile.getSize());
			if (uploadfile.getSize() > maxSize) {
				return responseErrorData(response, 1, "上传的图片大小不能超过4M。");
			}
			String[] type = fileType.split(",");

			setFileTypeList(type);

			String ext = FileUploadUtils.getSuffix(uploadfile.getOriginalFilename());
			if ((!fileType.contains(ext)) || ("jsp".equals(ext))) {
				return responseErrorData(response, 1, "文件格式错误，上传失败。");
			}
			String filePath = getPath(request, ext, param);
			File file = new File(getProjectRootDirPath(request) + filePath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			uploadfile.transferTo(file);

			return responseData(filePath, 0, "上传成功", response);
		} catch (Exception e) {
			logger.error("gok4()--error", e);
		}
		return responseErrorData(response, 2, "系统繁忙，上传失败");
	}

	@RequestMapping(value = { "/keupload" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	public String kindEditorUpload(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "param", required = false) String param, @RequestParam(value = "fileType", required = true) String fileType, @RequestParam(value = "pressText", required = false) String pressText) {
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile imgFile = multipartRequest.getFile("imgFile");
			if (imgFile == null) {
				return responseData("", 1, "请选择上传的文件，上传失败", response);
			}
			long maxSize = 4096000L;
			System.out.println(imgFile.getSize());
			if (imgFile.getSize() > maxSize) {
				return responseErrorData(response, 1, "上传的图片大小不能超过4M。");
			}
			String[] type = fileType.split(",");

			setFileTypeList(type);

			String ext = FileUploadUtils.getSuffix(imgFile.getOriginalFilename());
			if ((!fileType.contains(ext)) || ("jsp".equals(ext))) {
				return responseErrorData(response, 1, "文件格式错误，上传失败。");
			}
			String filePath = getPath(request, ext, param);
			File file = new File(getProjectRootDirPath(request) + filePath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			imgFile.transferTo(file);

			return responseData(filePath, 0, "上传成功", response);
		} catch (Exception e) {
			logger.error("kindEditorUpload()--error", e);
		}
		return responseErrorData(response, 2, "系统繁忙，上传失败。");
	}

	@RequestMapping(value = { "/shrinkDiagram" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public String kindEditorUploadShrinkDiagram(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "param", required = false) String param, @RequestParam(value = "fileType", required = true) String fileType, @RequestParam(value = "pressText", required = false) String pressText) {
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile imgFile = multipartRequest.getFile("imgFile");
			if (imgFile == null) {
				return responseData("", 1, "请选择上传的文件，上传失败", response);
			}
			long maxSize = 1024000L;
			System.out.println(imgFile.getSize());
			if (imgFile.getSize() > maxSize) {
				return responseErrorData(response, 1, "上传文件大小超过限制。");
			}
			String[] type = fileType.split(",");

			setFileTypeList(type);

			String ext = FileUploadUtils.getSuffix(imgFile.getOriginalFilename());
			if ((!fileType.contains(ext)) || ("jsp".equals(ext))) {
				return responseErrorData(response, 1, "文件格式错误，上传失败。");
			}
			String filePath = getPath(request, ext, param);
			File file = new File(getProjectRootDirPath(request) + filePath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			imgFile.transferTo(file);

			String width = request.getParameter("width");
			String height = request.getParameter("height");

			String smallUrl = zoomImage(request, filePath, Integer.valueOf(width).intValue(), Integer.valueOf(height).intValue());

			Map<String, Object> map = new HashMap();
			map.put("url", filePath);
			map.put("error", Integer.valueOf(0));
			map.put("message", "上传成功");
			map.put("smallurl", smallUrl);
			return gson.toJson(map);
		} catch (Exception e) {
			logger.error("kindEditorUpload()--error", e);
		}
		return responseErrorData(response, 2, "系统繁忙，上传失败。");
	}

	@RequestMapping({ "/saveface" })
	@ResponseBody
	public String saveface(HttpServletRequest request, HttpServletResponse response) {
		try {
			String photoPath = request.getParameter("photoPath");

			int imageWidth = Integer.parseInt(request.getParameter("txt_width"));

			int imageHeight = Integer.parseInt(request.getParameter("txt_height"));

			FileUploadUtils.changeSize(getProjectRootDirPath(request) + photoPath, getProjectRootDirPath(request) + photoPath, imageWidth, imageHeight);

			int cutTop = Integer.parseInt(request.getParameter("txt_top"));

			int cutLeft = Integer.parseInt(request.getParameter("txt_left"));

			int dropWidth = Integer.parseInt(request.getParameter("txt_DropWidth"));

			int dropHeight = Integer.parseInt(request.getParameter("txt_DropHeight"));

			String ext = FileUploadUtils.getSuffix(photoPath);
			String newPath = getPath(request, ext, "customer");
			FileUploadUtils.cut(getProjectRootDirPath(request) + photoPath, getProjectRootDirPath(request) + newPath, cutLeft, cutTop, dropWidth, dropHeight);

			File file = new File(getProjectRootDirPath(request) + photoPath);
			if (file.exists()) {
				file.delete();
			}
			long maxSize = 4096000L;
			System.out.println(file.length());
			if (file.length() > maxSize) {
				return responseErrorData(response, 1, "上传的图片大小不能超过4M。");
			}
			Map<String, Object> map = new HashMap();
			map.put("src", newPath);
			map.put("status", "1");
			return gson.toJson(map);
		} catch (Exception e) {
			logger.error("saveface()---error", e);
		}
		return null;
	}

	@RequestMapping({ "/pdfUploadAndImg" })
	@ResponseBody
	public String pdfUploadAndImg(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "param", required = false) String param) {
//		Map<String, String> map = new HashMap();
//		try {
//			String width = request.getParameter("width");
//			String height = request.getParameter("height");
//
//			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//			MultipartFile imgFile = multipartRequest.getFile("fileupload");
//
//			String ext = FileUploadUtils.getSuffix(imgFile.getOriginalFilename());
//			if ("jsp".equals(ext)) {
//				return responseErrorData(response, 1, "文件格式错误，上传失败。");
//			}
//			String filePath = getPath(request, ext, param);
//			File file = new File(getProjectRootDirPath(request) + filePath);
//			if (!file.getParentFile().exists()) {
//				file.getParentFile().mkdirs();
//			}
//			imgFile.transferTo(file);
//
//			Map<String, String> pdfToPngmap = PDFUtils.pdfToPng(getProjectRootDirPath(request), getProjectRootDirPath(request) + filePath, width, height);
//			map.put("pdfUrl", filePath);
//			map.put("pngUrlStrs", pdfToPngmap.get("pngUrlStrs"));
//			map.put("pngUrlStrsTB", pdfToPngmap.get("pngUrlStrsTB"));
//
//			return gson.toJson(map);
//		} catch (Exception e) {
//			logger.error("pdfUploadAndImg error", e);
//		}
		return null;
	}

	@RequestMapping({ "/uploadfile" })
	@ResponseBody
	public String uploadfile(HttpServletResponse response, HttpServletRequest request, @RequestParam(value = "param", required = false) String param) {
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile imgFile = multipartRequest.getFile("fileupload");

			String ext = FileUploadUtils.getSuffix(imgFile.getOriginalFilename());
			if ("jsp".equals(ext)) {
				return responseErrorData(response, 1, "文件格式错误，上传失败。");
			}
			String filePath = getPath(request, ext, param);
			File file = new File(getProjectRootDirPath(request) + filePath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			imgFile.transferTo(file);

			logger.info("++++upload img return:" + filePath);
			return filePath;
		} catch (Exception e) {
			logger.error("uploadfile error", e);
		}
		return null;
	}

	@RequestMapping(value = { "/deletefile" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> deleteFile(HttpServletRequest request, @RequestParam(value = "filePath", required = true) String filePath) {
		Map<String, Object> json = new HashMap();
		try {
			if ((filePath != null) && (filePath.trim().length() > 0) && (filePath.startsWith("/images/upload/"))) {
				File file = new File(getProjectRootDirPath(request) + filePath);
				if (file.exists()) {
					file.delete();
					json = setJson(true, "文件删除成功", null);
				} else {
					json = setJson(false, "文件不存在，删除失败", null);
				}
			} else {
				json = setJson(false, "删除失败", null);
			}
		} catch (Exception e) {
			json = setJson(false, "系统繁忙，文件删除失败", null);
			logger.error("deleteFile()--error", e);
		}
		return json;
	}

	private String getPath(HttpServletRequest request, String ext, String param) {
		String filePath = "/images/upload/";
		if ((param != null) && (param.trim().length() > 0)) {
			filePath = filePath + param;
		} else {
			filePath = filePath + CommonConstants.projectName;
		}
		filePath = filePath + "/" + DateUtils.toString(new Date(), "yyyyMMdd") + "/" + System.currentTimeMillis() + "." + ext;
		return filePath;
	}

	public String responseData(String path, int error, String message, HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap();
		map.put("url", path);
		map.put("error", Integer.valueOf(error));
		map.put("message", message);
		response.getWriter().write(gson.toJson(map));
		return null;
	}

	public String responseErrorData(HttpServletResponse response, int error, String message) {
		try {
			Map<String, Object> map = new HashMap();
			map.put("error", Integer.valueOf(error));
			map.put("message", message);
			response.setContentType("application/json; charset=UTF-8");
			response.getWriter().print(gson.toJson(map));
			response.getWriter().flush();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return null;
	}

	public void setFileTypeList(String[] type) {
		this.fileTypeList = new ArrayList();
		for (String _t : type) {
			this.fileTypeList.add(_t);
		}
	}

	public String zoomImage(HttpServletRequest request, String srcFileName, int width, int height) {
		String tagFileName = srcFileName.substring(0, srcFileName.lastIndexOf(".")) + "-small" + srcFileName.substring(srcFileName.lastIndexOf("."), srcFileName.length());
		srcFileName = getProjectRootDirPath(request) + srcFileName;
		try {
			BufferedImage bufferedImage = ImageIO.read(new File(srcFileName));

			int srcWidth = bufferedImage.getWidth();
			int srcHeight = bufferedImage.getHeight();
			float _scale = Float.valueOf(width).floatValue() / srcWidth;
			srcHeight = (int) (Float.valueOf(srcHeight).floatValue() * _scale);

			Image image = bufferedImage.getScaledInstance(width, srcHeight, 4);

			ImageFilter cropFilter = new CropImageFilter(0, 0, width, height);
			Image img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
			BufferedImage outputImage = new BufferedImage(width, height, 1);
			Graphics g = outputImage.getGraphics();
			g.drawImage(img, 0, 0, width, height, null);
			g.dispose();

			ImageIO.write(outputImage, FileUploadUtils.getSuffix(getProjectRootDirPath(request) + tagFileName), new File(getProjectRootDirPath(request) + tagFileName));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return tagFileName;
	}
}
